package com.kehao.accountbook.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.kehao.accountbook.AccountApplication;
import com.kehao.accountbook.MainActivity;
import com.kehao.accountbook.ModifyExpendActivity;
import com.kehao.accountbook.R;
import com.kehao.accountbook.adapter.ExpenditureAdapter;
import com.kehao.accountbook.network.Network;
import com.kehao.accountbook.pojo.Expenditure;
import com.kehao.accountbook.pojo.SimpleDate;
import com.kehao.accountbook.pojo.SimpleTime;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HistoryAccountFragment extends Fragment implements View.OnClickListener {
    EditText et_year;
    EditText et_month;
    Button btn_query;
    TextView tv_pay;
    TextView tv_get;
    RecyclerView recyclerView;
    public static final int REQUEST_CODE_MODIFY_EXPEND = 2;
    private static final int RESULT_CODE_DELETE = 10;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_history_account, container, false);
        SimpleDate todayDate = new SimpleDate();
        et_year = view.findViewById(R.id.et_year);
        et_month = view.findViewById(R.id.et_month);
        et_year.setText(todayDate.getYear()+"");
        et_month.setText(todayDate.getMonth()+"");
        btn_query = view.findViewById(R.id.btn_query);
        btn_query.setOnClickListener(this);
        tv_pay = view.findViewById(R.id.tv_pay);
        tv_get = view.findViewById(R.id.tv_get);
        recyclerView = view.findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);
        ExpenditureAdapter adapter = new ExpenditureAdapter(new ArrayList<Expenditure>());
        adapter.listener = new ExpenditureAdapter.ItemClickListener(){
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(getActivity(), ModifyExpendActivity.class);
                intent.putExtra("item",((ExpenditureAdapter)recyclerView.getAdapter()).expenditureList.get(position));
                startActivityForResult(intent,REQUEST_CODE_MODIFY_EXPEND);
            }
        };
        recyclerView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_query:
                List list = updateList();
                recyclerView.getAdapter().notifyDataSetChanged();
                updatePayAndGet(list);
                break;
        }
    }

    private List updateList() {
        SimpleDate date = new SimpleDate(Integer.parseInt(et_year.getText().toString()),
                Integer.parseInt(et_month.getText().toString()));
        List list = ((ExpenditureAdapter)recyclerView.getAdapter()).expenditureList;
        list.clear();
        //在网络上同步数据
        getAccountApplication().syncData(date.getYear(),date.getMonth());
        //再查询出来
        list = ((ExpenditureAdapter)recyclerView.getAdapter()).expenditureList
                = LitePal.where("month = ? and year = ? and username = ? and status != ?",Integer.toString(date.getMonth()),
                Integer.toString(date.getYear()),getAccountApplication().getUsername(),Integer.toString(Expenditure.STATUS_REMOVE))
                .order("day , hour , min , second")
                .find(Expenditure.class);
        return list;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<Expenditure> list = ((ExpenditureAdapter)recyclerView.getAdapter()).expenditureList;
        SimpleDate todayDate = new SimpleDate();
        switch (requestCode){
            case REQUEST_CODE_MODIFY_EXPEND:
                if(resultCode == Activity.RESULT_OK){
                    updateList();
                    Expenditure expenditure = (Expenditure) data.getSerializableExtra("item");
                    for(int i =0;i<list.size();i++){
                        Expenditure e = list.get(i);
                        if(e.getDay()==expenditure.getDay() &&e.getHour()==expenditure.getHour()
                                &&e.getMin()==expenditure.getMin()&&e.getSecond()==expenditure.getSecond()){
                            e.setType(expenditure.getType());
                            e.setComment(expenditure.getComment());
                            e.setMoney(expenditure.getMoney());
                            e.setStatus(Expenditure.STATUS_LOCAL_CHANGE);
                            e.save();
                            recyclerView.getAdapter().notifyItemChanged(i);
                            break;
                        }
                    }
                    if(expenditure.getYear()==todayDate.getYear()&&expenditure.getMonth()==todayDate.getMonth()){//如果是本月的日期，首页也要重新加载
                        MainActivity activity = (MainActivity) getActivity();
                        MainFragment fragment = (MainFragment) activity.getFragments().get(0);
                        fragment.refreshView();
                    }
                    getAccountApplication().syncData(expenditure.getYear(),expenditure.getMonth());
                    Log.e("HistoryFragment", "onActivityResult:modify ok "+expenditure.toString() );
                }
                else if(resultCode==RESULT_CODE_DELETE){
                    updateList();
                    Expenditure expenditure = (Expenditure) data.getSerializableExtra("item");
                    for(int i =0;i<list.size();i++){
                        Expenditure e = list.get(i);
                        if(e.getDay()==expenditure.getDay() &&e.getHour()==expenditure.getHour()
                                &&e.getMin()==expenditure.getMin()&&e.getSecond()==expenditure.getSecond()){
                            /*e.delete();是真删除，假删除是在anchor上做标记
                            * */
                            e.setStatus(Expenditure.STATUS_REMOVE);
                            e.save();
                            list.remove(i);
                            recyclerView.getAdapter().notifyDataSetChanged();
                            break;
                        }
                    }
                    if(expenditure.getYear()==todayDate.getYear()&&expenditure.getMonth()==todayDate.getMonth()){//如果是本月的日期，首页也要重新加载
                        MainActivity activity = (MainActivity) getActivity();
                        MainFragment fragment = (MainFragment) activity.getFragments().get(0);
                        fragment.refreshView();
                    }
                    Log.e("HistoryFragment", "onActivityResult:remove ok "+expenditure.toString() );
                    getAccountApplication().syncData(expenditure.getYear(),expenditure.getMonth());
                }
                else {
                    Log.e("HistoryFragment", "onActivityResult: cancel" );
                }
                break;
        }
        updatePayAndGet(list);
    }

    private void updatePayAndGet(List<Expenditure> list) {
        double pay = 0;
        double get = 0;
        for (Expenditure i :list){
            double money = i .getMoney();
            if(money>0){
                get+=money;
            }else if(money<0){
                pay+=money;
            }
        }
        if(pay!=0){
            tv_pay.setText("月支出: "+(-pay));
        }else {
            tv_pay.setText("月支出：暂无支出");
        }
        if(get!=0){
            tv_get.setText("月收入： "+get);
        }else {
            tv_get.setText("月收入： 暂无收入");
        }
    }

    private AccountApplication getAccountApplication(){
        return (AccountApplication)getActivity().getApplication();
    }

}
